***Simplified Version 5&6 - Generating consolidated variables
*This version should work with sample datafiles, with brief steps and all intermediate variables have been removed. The original do files used in the paper are 5- consolidated variables-01 & 6- consolidated variables-02.



*cd "/RFS_replication_package/Martinsson_et_al_datasets"


*Corporate structure
clear all
use kth_knc_201907.dta
rename PeOrgNrD_LopNr bidnr 
g year = year(kboksl)
merge 1:1 bidnr year using  "master_file_with_fuels_emissions_w_inv.dta"
g sf = 1 if PeOrgNrK_LopNr == .
replace sf = 0 if sf == .
replace PeOrgNrK_LopNr = bidnr if PeOrgNrK_LopNr == .
drop _merge
save noemission_req_KNC_merged.dta ,replace


*Firm age
use age_serrano, replace 
g founded_n = year(ser_regdat)
drop ser_regdat
merge 1:m bidnr using noemission_req_KNC_merged.dta
drop _merge
bysort PeOrgNrK_LopNr : egen con_founded_n = min(founded_n)
save "stockmarket_age.dta", replace 


*Trade market
use kth_stock_202211.dta, replace 
rename peorgnr_LopnNr bidnr
g year = year(day)
merge 1:1 bidnr year using "stockmarket_age.dta"

g sse = 1 if marketname == "SSE"
g o_m = 1 if sse == .
foreach v of varlist sse  o_m{
	replace `v' = 0 if `v' == .
}

bysort PeOrgNrK_LopNr year: egen con_sse = max(sse)
g con_o_m = 0 if con_sse == 1
replace con_o_m = 1 if con_sse == 0
drop if _merge == 1
drop day marketname _merge 
save "stockmarket_pri.dta",replace 

use "stockmarket_pri.dta",replace 

*Consolidated accounting vars
use con_vars_intermediate.dta, replace 
merge 1:1 bidnr year using "stockmarket_pri.dta"
replace dividend = utdbel if dividend == .
drop utdbel
replace ta_defl = ta/defl_2010 if ta_defl == .

foreach i of varlist dividend ta total_debt sales_ppi_12month sales_defl_12month ta_defl cash_flow_defl{
	bysort PeOrgNrK_LopNr year: egen con_`i' = total(`i') if sf == 0 
	bysort PeOrgNrK_LopNr year: replace con_`i' = `i' if sf == 1 
	bysort PeOrgNrK_LopNr year: replace con_`i' =. if (con_`i' == 0 &`i' == .) | (year < 1996)
}

drop if _merge == 1 
drop _merge 
keep PeOrgNrK_LopNr bidnr year founded_n con_founded_n sf - con_cash_flow_defl
order PeOrgNrK_LopNr bidnr year

merge 1:1 bidnr year using "master_file_with_fuels_emissions_w_inv.dta" 
keep if _merge == 3
drop _merge 

*PACE
**Files are produced by codes 6a- PACE_capstock, 6b- PACE_review, 6c- PACE_code 
merge m:1 sni2007_4d using "PACE_realcapstock_2.dta"
drop if _merge==2
drop _merge

merge m:1 sni2007_4d using "PACE_sni2007_stat_2.dta"
drop if _merge==2
drop _merge

order PeOrgNrK_LopNr bidnr year tj - sum_OPX
sort PeOrgNrK_LopNr year bidnr, stable

save "master_file_with_fuels_emissions_w_inv_v2_new.dta",replace